﻿using JD.IRCDIS.Instruction;
using NutShell.DesignPattern;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SerialPortReceiveTestApp
{
        public partial class MainForm : Form
        {
                private SerialPort sp;

                public MainForm()
                {
                        InitializeComponent();
                }

                private void MainForm_Load(object sender, EventArgs e)
                {
                        Singleton<SerialPortInstruction>.Instance.PortName = "COM2";
                        sp = Singleton<SerialPortInstruction>.Instance.SerialPort;
                        sp.DataReceived += SerialPort_DataReceived;
                }

                void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
                {
                        if (sp.BytesToRead != 0)
                        {
                                Byte[] buffer = new Byte[sp.BytesToRead];
                                sp.Read(buffer, 0, sp.BytesToRead);

                                StringBuilder sb = new StringBuilder();
                                foreach (var item in buffer)
                                {
                                        sb.Append(item);
                                        sb.Append(" ");

                                }

                                textBox1.Text += sb.ToString();
                        }
                }

                private void button1_Click(object sender, EventArgs e)
                {
                        Singleton<SerialPortInstruction>.Instance.SendValidateInstruction();
                }

                private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
                {
                        sp.Close();
                }
        }
}
